import time
import requests
import json
from PyCmpltrtok.common import sep

if '__main__' == __name__:
    
    import argparse
    
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('names', help='key words to search', nargs='*', default=["最终幻想8重制版"])
    args = parser.parse_args()
    names = args.names
    
    # subscription_key = '8a29dfcf61cc4d92b50c3de636d4cdb4'
    subscription_key = '8e2dc08127314251a9ec52fde6d37546'
    assert subscription_key

    # search_url = "https://api.bing.microsoft.com/v7.0/search"
    search_url = "https://api.bing.microsoft.com/v7.0/custom/search"
    # search_url = "https://api.bing.microsoft.com/"
    headers = {"Ocp-Apim-Subscription-Key": subscription_key}
    
    for name in names:
        sep(name)
        params = {
            "q": name,
            "textDecorations": True,
            "textFormat": "HTML",
            "customConfig": "716c46ae-d1fa-40e7-ae91-23bb113412f3",
            # "mkt": "en-US",
            "mkt": "zh-CN",
        }
        response = requests.get(search_url, headers=headers, params=params)
        response.raise_for_status()
        search_results = response.json()

        print(search_results)
        with open(f'{name}.tmp.json', 'w', encoding='utf8') as f:
            json.dump(search_results, f, ensure_ascii=False)
            
        time.sleep(1.0)
